package com.tbsoft.ehr.service.contract;

import java.util.Calendar;
import java.util.List;

import com.tbsoft.ehr.dao.contract.ContractDao;
import com.tbsoft.ehr.model.Contract;
import com.tbsoft.ehr.model.ContractVo;
import com.tbsoft.ehr.model.StaffInfo;

public class ContractServiceImpl implements ContractService {

	private ContractDao contractDao;
	
	public ContractDao getContractDao() {
		return contractDao;
	}

	public void setContractDao(ContractDao contractDao) {
		this.contractDao = contractDao;
	}

	public Contract addContract(Contract contract) {		
		return this.contractDao.save(contract);
	}

	public List<Contract> getContractByStaff(StaffInfo staff) {
		return this.contractDao.getContractByStaffId(staff.getStaffId());
	}

	@Override
	public List<Contract> getContractByCondton(List<StaffInfo> staffLst,
			String endTimeFrom, String endTimeTo,int startIndex,int count) {
		return this.contractDao.getContractByCondton(staffLst, endTimeFrom, endTimeTo,startIndex,count);
	}

	@Override
	public int getContractCount(List<StaffInfo> staffLst,String endTimeFrom, String endTimeTo) {
		return this.getContractDao().getContractCount(staffLst,endTimeFrom,endTimeTo);
	}
	
	/**
	 * 根据合同信息构造合同vo对象
	 * list顺序以合同截止时间降序排列
	 * 
	 * @param contractLst
	 * @return
	 */
	public ContractVo genContractInfo(List<Contract> contractLst){
		ContractVo vo = new ContractVo();

		//设置第一份合同开始时间为入职时间
		vo.setTheFirstStartTime(contractLst.get(0).getStaff().getEntrydate());
		
		//设置最新的合同开始结束时间
		Contract ct2 = contractLst.get(0);
		vo.setTheLastStartTime(ct2.getStartTime());
		vo.setTheLastEndTime(ct2.getEndTime());

		//统计工作年限
		Calendar startTime = Calendar.getInstance();
		startTime.setTime(vo.getTheFirstStartTime());
		
		Calendar endTime = Calendar.getInstance();
		endTime.setTime(ct2.getEndTime());

		//验证当年时间去最新合同结束时间的先后关系
		Calendar currtTime = Calendar.getInstance();
		if(endTime.before(currtTime)){
			currtTime = endTime;
		}
		int year = currtTime.get(Calendar.YEAR)-startTime.get(Calendar.YEAR);
		currtTime.set(Calendar.YEAR, startTime.get(Calendar.YEAR));
		if(currtTime.before(startTime)){
			year-=1;
		}
		vo.setWorkYear(year);
		//是否续签
		if(contractLst.size()>1){
			vo.setContinued("Y");
		} 
		return vo;
	}

}
